<?php
namespace app\model\question;

use think\Model;

class ZxlKnowStoreQuestionUserStatisticsModel extends Model
{
    protected $name = 'zxl_know_store_question_user_statistics';

    /**
     * 更新用户刷题进度
     * 
     * @return bool
     */
    public static function UpdateUserData($chapter, $userId, $mId, $libId){
        // 题目所属章节进度更新
        $model = self::where([
            "user_id" => $userId,
            "target_id" => $chapter->id,
            "sta_type" => "chapter",
        ])
        ->order("update_time", "desc")
        ->findOrEmpty();
        // 找到章节练习的子集
        $allchapterIds = ZxlKnowStoreQuestionChapterModel::where(function($q) use($chapter){
            $q->where("pid", $chapter->id)
            ->whereOr("id", $chapter->id);
        })->column("id");
        $data = self::saveStatistics($allchapterIds, $userId);
        if($model->isEmpty()){
            $model->user_id = $userId;
            $model->target_id = $chapter->id;
            $model->sta_type = "chapter";
            $model->lib_id = $libId;
            $model->m_id = $mId;
        } else {
            self::where([
                "user_id" => $userId,
                "target_id" => $chapter->id,
                "sta_type" => "chapter"
            ])->where("id", "<>", $model->id)->delete();
        }
        $model->practice_number = $data['practiceNumber'];
        $model->right_number =$data['rightNumber'];
        $model->total_number = $data['totalNumber'];
        $model->right_rate = $data['rightRate'];
        $model->save();
        // 清空该章节以及二级章节下的做题进度
        $subChapterIds =  ZxlKnowStoreQuestionChapterModel::where("pid", $chapter->id)->column("id");
        foreach($subChapterIds as $subChapterId){
            $submodel = self::where([
                "user_id" => $userId,
                "target_id" => $subChapterId,
                "sta_type" => "chapter",
            ])
            ->order("update_time", "desc")
            ->findOrEmpty();
            if($submodel->isEmpty()){
                $submodel->user_id = $userId;
                $submodel->target_id = $subChapterId;
                $submodel->sta_type = "chapter";
                $submodel->lib_id = $libId;
                $submodel->m_id = $mId;
            } else {
                self::where([
                    "user_id" => $userId,
                    "target_id" => $subChapterId,
                    "sta_type" => "chapter"
                ])->where("id", "<>", $submodel->id)->delete();
            }
            $data = self::saveStatistics([$subChapterId], $userId);
            $submodel->practice_number = $data['practiceNumber'];
            $submodel->right_number = $data['rightNumber'];
            $submodel->total_number = $data['totalNumber'];
            $submodel->right_rate = $data['rightRate'];
            $submodel->save();
        }
        
        // 更新上一级章节的做题记录
        if($chapter->pid > 0) {
            self::processParentChapterSimple($chapter, $userId, $libId, $mId);
        }
    }

    /**
     * 更新父级章节记录
     * 
     * @return bool
     */
    private static function processParentChapterSimple($chapter, $userId, $libId, $mId) {
        $chapterIds = ZxlKnowStoreQuestionChapterModel::where(function($q) use($chapter){
            $q->whereIn("pid", $chapter->pid)
            ->whereOr("id", $chapter->pid);
        })->column("id");
        $data = self::saveStatistics($chapterIds, $userId);
        $pmodel = self::where([
            "user_id" => $userId,
            "target_id" => $chapter->pid,
            "sta_type" => "chapter"
        ])
        ->order("update_time", "desc")
        ->findOrEmpty();
        if($pmodel->isEmpty()){
            $pmodel->user_id = $userId;
            $pmodel->target_id = $chapter->pid;
            $pmodel->lib_id = $libId;
            $pmodel->sta_type = "chapter";
            $pmodel->m_id = $mId;
        } else {
            self::where([
                "user_id" => $userId,
                "target_id" => $chapter->pid,
                "sta_type" => "chapter",
            ])
            ->where("id", "<>", $pmodel->id)
            ->delete();
        }
        $pmodel->practice_number = $data['practiceNumber'];
        $pmodel->right_number =$data['rightNumber'];
        $pmodel->total_number = $data['totalNumber'];
        $pmodel->right_rate = $data['rightRate'];
        $pmodel->save();
    }

    /**
     * 统计章节训练的做题情况
     * 
     * @return array
     */
    public static function saveStatistics($chapterIds, $userId) {
        $where = [
            "user_id" => $userId,
            "is_statics" => 1 
        ];
        $practiceNumber = ZxlKnowStoreQuestionPracticeDetailModel::where($where)->whereIn("main_id", $chapterIds)->group("question_id")->count();
        // 正确数量
        $rightNumber = ZxlKnowStoreQuestionPracticeDetailModel::where($where)->whereIn("main_id", $chapterIds)->where("is_correct", 1)->count();
        // 练题总数
        $totalNumber = ZxlKnowStoreQuestionPracticeDetailModel::where($where)->whereIn("main_id", $chapterIds)->count();
        $rightRate = 0;
        if($rightNumber > 0 && $totalNumber > 0){
            $rightRate =  bcmul(bcdiv($rightNumber, $totalNumber, 4), 100, 2);
        }
        return [
            "practiceNumber" => $practiceNumber,
            "rightNumber"    => $rightNumber,
            "totalNumber"    => $totalNumber,
            "rightRate"      => $rightRate
        ];
    }

}